package threads;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Package: threads
 * Description： CountDownLatch
 * Author: Forest
 * Date: Created in 2021/4/8 14:57
 * Version: 0.0.1
 * Modified By: duforest
 */
public class ThreadTest extends ThreadGroup {

    private ThreadTest() {
        super("ThreadTest");
    }


    public static void main(String[] args) {

        AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(new ThreadTest(), new Runnable() {
            @Override
            public void run() {
                int num = 3 / 0;
            }
        }).start();
        new Thread(new ThreadExceptionRunner(atomicBoolean)).start();
        countDownLatch.countDown();
        try {
            countDownLatch.await(1, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (!atomicBoolean.get()) {
            System.out.println("happen error, fast System.exit");
            return;
        }

        System.out.println("main do something");
    }

    /**
     * 当线程抛出unckecked异常时,系统会自动调用该函数,但是是在抛出异常的线程内执行
     *
     * @param thread
     * @param exception
     */
    public void uncaughtException(Thread thread, Throwable exception) {
        System.out.println("thread name=" + thread.getName() + thread.getId());
        exception.printStackTrace();//example,   print   stack   trace
    }
}